package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Permission;
import com.itheima.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Service(interfaceClass = PermissionService.class)
@RestController
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    public PermissionDao permissionDao;
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<Permission> page = permissionDao.findPage(queryString);
        long total = page.getTotal();
        List<Permission> rows = page.getResult();
       return  new PageResult(total,rows);

    }

    @Override
    public void add(Permission permission) {
        String name = permission.getName();
        String enable = permission.getEnable();
        if(name !=null && name.length()>0){
              if(enable !=null && enable.length()>0){
                  permissionDao.add(permission);
              }
        }
    }

    @Override
    public Permission findById(Integer id) {
        Permission permission = permissionDao.findById(id);

        return permission;
    }

    @Override
    public void edit(Permission permission) {

        permissionDao.edit(permission);
    }

    @Override
    public void delete(Integer id) throws RuntimeException {
        Long count = permissionDao.findRoleAndPermissionById(id);
        if(count>0){
            throw new RuntimeException("当前权限被引用，不能删除");
        }
        permissionDao.delete(id);
    }


}
